import ToolBarComponent from "../components/command/toolbar/component/fd-toolbar";

export class OperateUtils {

    static hasClass(obj, cls) {
        return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
    }

    static addClass(obj, cls) {
        if (!this.hasClass(obj, cls)) obj.className += " " + cls;
    }

    static removeClass(obj, cls) {
        if (this.hasClass(obj, cls)) {
            var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
            obj.className = obj.className.replace(reg, ' ');
        }
    }

    static toggleClass(obj, cls) {
        if (this.hasClass(obj, cls)) {
            this.removeClass(obj, cls);
        } else {
            this.addClass(obj, cls);
        }
    }
    /**
     * 处理Tab、Section工具栏对应的按钮结构
     */
    static getTabToolbarStr(toolbar, options?, element?: any) {
        if (!toolbar) {
            return '';
        }
        if (!toolbar.hasOwnProperty('contents')) {
            return '';
        }
        const tabPageToolBarComponent = new ToolBarComponent(toolbar, options);
        tabPageToolBarComponent.init();
        tabPageToolBarComponent.rebuild();
        const toolBtnsStr = tabPageToolBarComponent.render();
        tabPageToolBarComponent.attach(element);
        // toolbar.contents.forEach(btnItem => {
        //     let btnCls = btnItem.appearance && btnItem.appearance.class ? btnItem.appearance.class : "btn btn-secondary";
        //     let isDisabled = btnItem.disable == true ? ' disabled' : '';
        //     toolBtnsStr += `<button id="${btnItem.id}" class="${btnCls}" ${isDisabled}>${btnItem.title}</button>`;
        // });
        return toolBtnsStr;
    }
    /*
     * 处理响应式工具栏、Sidebar对应的按钮结构
    */
    static getResponseToolbarStr(toolbar, size = 'default') {
        if (!toolbar) {
            return '';
        }
        let toolbarDatas = [];
        if (Array.isArray(toolbar)) {
            toolbarDatas = toolbar;
        } else if (toolbar.hasOwnProperty('items')) {
            toolbarDatas = toolbar.items;
        } else {
            return '';
        }
        let toolBtnsStr = "";
        toolbarDatas.forEach(btnItem => {
            // 新footer和header上构造的结构中没有appearance这个样式
            let btnCls =
                btnItem.appearance && btnItem.appearance.class
                    ? " " + btnItem.appearance.class
                    : (btnItem.class ? " " + btnItem.class : " btn-secondary");
            btnCls += btnItem.disable === true ? " disabled" : "";
            btnCls += size == 'default' ? '' : ' btn-' + size;
            toolBtnsStr += `<button class="btn  f-rt-btn f-btn-mr ${btnCls}" id="${btnItem.id}">
                  ${btnItem.text}
              </button>`;
        });
        return toolBtnsStr;
    }
    /**
     *  获取ViewChange的字符串
     * @param toolbarData 
     * @param viewType 
     * @param currentItem 
     */
    static getViewChangeStr(toolbarData, viewType, currentItem) {
        if (toolbarData.length == 0) {
            return `<div class="f-view-change">未配置</div>`;
        }
        let result = '';
        let btnsStr = '';
        if (viewType == 'tile') {
            // 如果是平铺
            toolbarData.forEach(item => {
                let btnCls = item.type == currentItem.type ? ' tile-btn-active' : '';
                btnCls += item.disable == true ? ' tile-btn-disable' : '';
                btnsStr += ` <div class="f-view-change-tile-btn ${btnCls}" title="${item.title}" viewChange="${item.type}">
                <span class="tile-btn-icon ${item.iconName}"></span>
                </div>`;
            });
            result = `<div class="f-view-change-tile">
               ${btnsStr}
            </div>`
        } else {
            toolbarData.forEach(item => {
                let btnCls = item.type == currentItem.type ? ' typelist-item-active' : '';
                btnCls += item.disable == true ? ' tile-btn-disable' : '';
                btnsStr += `<li class="typelist-item ${btnCls}" title="${item.title}" viewChange="${item.type}">
                <span class="tile-btn-icon "></span>
                <span class="typelist-item-icon ${item.iconName}"></span>
                <span class="typelist-item-title">${item.title}</span>
                </li>`;
            });
            result = ` <div class="f-view-change-dropdown"> 
                <div class="f-view-change-toggle">
                    <span class="toggle-btn-icon ${currentItem.iconName}"></span>
                </div>
                <div class="f-view-change-typelist">
                    <div class="f-view-change-typelist-content">
                        <div class="f-view-change-typelist-arrow"></div>
                            <ul class="f-view-change-typelist-list">
                                ${btnsStr}
                            </ul>
                         </div>
                    </div>
                </div>`;
        }
        return result;
    }
    /**
     * 查找父元素
     * @param ele 
     */
    static getFormParent(ele) {
        if (ele.parentElement == document.body) {
            return null;
        }
        if (ele.parentElement.hasAttribute('ref') && ele.parentElement.getAttribute('ref') == "form") {
            return ele.parentElement;
        } else {
            return this.getFormParent(ele.parentElement);
        }
    }
    /**
     * 
     * @param eventListener 绑定事件的方式
     * @param viewChangeDatas viewchange的数据
     * @param activeTypeItem 当前类型的项
     * @param relatedElements {parentEl:查找的父元素,viewItems:找到的同一个groupId下的viewContainer项,viewChangeEl:viewChange元素}
     * @param tileBtns 
     * @param afterClickFunc 
     */
    static bindTileEventForViewChange(eventListener, viewChangeDatas, activeTypeItem, viewChangeEl, beforeClickFunc = null, afterClickFunc = null) {
        if (!viewChangeEl) {
            return;
        }
        const tileBtns = viewChangeEl.querySelectorAll('.f-view-change-tile-btn');
        if (tileBtns) {
            tileBtns.forEach(tileBtn => {
                eventListener(tileBtn, 'click', (event) => {
                    event.stopPropagation();
                    if (beforeClickFunc) {
                        // 获取相关值
                        let { multiViewContainerEl } = beforeClickFunc();
                        activeTypeItem = this.viewChangeBtnClick(tileBtn, activeTypeItem, viewChangeDatas, multiViewContainerEl);
                    }
                    if (afterClickFunc) {
                        afterClickFunc(activeTypeItem);
                    }
                    // this.redraw();
                });
            });
        }
    }
    /**
     * 
     * @param eventListener 绑定事件的方式
     * @param viewChangeDatas  viewchange的数据
     * @param activeTypeItem 当前类型的项
     * @param parentEl:查找的父元素viewItems:找到的同一个groupId下的viewContainer项,viewChangeEl:viewChange元素
     * @param afterClickFunc 
     */
    static bindDropdownEventForViewChange(eventListener, viewChangeDatas, activeTypeItem, viewChangeEl, beforeClickFunc = null, afterClickFunc = null) {
        //下拉            
        // 展开收起下拉面板
        const viewDropdown = viewChangeEl.querySelector('.f-view-change-dropdown');
        const viewDroppanel = viewChangeEl.querySelector('.f-view-change-typelist');
        // 按钮
        const listItems = viewChangeEl.querySelectorAll('.typelist-item');
        listItems.forEach(tileBtn => {
            eventListener(tileBtn, 'click', (event) => {
                event.stopPropagation();
                if (beforeClickFunc) {
                    // 获取相关值
                    let { multiViewContainerEl } = beforeClickFunc();
                    activeTypeItem = this.viewChangeBtnClick(tileBtn, activeTypeItem, viewChangeDatas, multiViewContainerEl);
                    if (afterClickFunc) {
                        afterClickFunc(activeTypeItem);
                    }
                }
                viewDroppanel.style.display = 'none';
            });
        });
        eventListener(viewDropdown, 'mouseenter', (event) => {
            event.stopPropagation();
            viewDroppanel.style.display = 'block';
        });
        eventListener(viewDropdown, 'mouseleave', (event) => {
            event.stopPropagation();
            viewDroppanel.style.display = 'none';
        });
    }
    /**
     * 
     * @param tileBtn 当前点击的按钮
     * @param activeTypeItem 当前Type项
     * @param viewChangeDatas viewchange的数据
     * @param parentEl 查找的父元素
     * @param viewContainerItems 查找到的项
     */
    static viewChangeBtnClick(tileBtn, activeTypeItem, viewChangeDatas, viewContainerItems) {
        let activeType = tileBtn.getAttribute('viewChange');
        if (activeType != activeTypeItem.type) {
            this.changeRelatedViewItem(viewContainerItems, activeType);
            // 设定当前 --不能变更当前activeTypeItem
            activeTypeItem = this.viewChangeInitActiveItem(activeType, activeTypeItem, viewChangeDatas);
        }
        return activeTypeItem;
    }
    /**
     * 根据当前项，通过DOM操作改变viewchange状态
     * @param activeTypeItem 
     * @param viewChangeEl 
     */
    static updateTileByActiveType(viewType, activeTypeItem, viewChangeEl) {
        if (!activeTypeItem) {
            return;
        }
        if (viewType == 'tile') {
            const tileBtns = viewChangeEl.querySelectorAll('.f-view-change-tile-btn');
            if (tileBtns) {
                let findType = false;
                tileBtns.forEach(tileBtn => {
                    let activeType = tileBtn.getAttribute('viewChange');
                    if (activeType == activeTypeItem.type) {
                        findType = true;
                        this.addClass(tileBtn, 'tile-btn-active');
                    } else {
                        this.removeClass(tileBtn, 'tile-btn-active');
                    }
                });
                if (!findType) {
                    this.addClass(tileBtns[0], 'tile-btn-active');
                }
            }
        } else if (viewType == 'dropdown') {
            const dropBtn = viewChangeEl.querySelectorAll('.toggle-btn-icon');
            dropBtn.className = 'toggle-btn-icon ' + activeTypeItem.iconName;
        }
    }
    /**
     * 
     * @param parentEl 查找的范围元素
     * @param multiViewContainerEl 对应的viewContainer元素
     * @param viewChangeType 
     * @param viewGroupId 
     */
    static changeRelatedViewItem(multiViewContainerEl, viewChangeType) {
        if (!multiViewContainerEl) {
            return;
        }
        const multiViewContainerInstance = multiViewContainerEl.componentInstance;
        if (!multiViewContainerInstance || !multiViewContainerInstance.updateCurrentViewItem) {
            return;
        }
        multiViewContainerInstance.updateCurrentViewItem(viewChangeType);
    }
    /**----------------------此处的逻辑可能有问题，activeTypeItem可能无用
     * viewChange数据中获取当前项
     * @param activeType 当前Type类型
     * @param activeTypeItem 当前TypeItem项
     * @param viewChangeDatas viewChange数据
     */
    static viewChangeInitActiveItem(activeType, activeTypeItem, viewChangeDatas) {
        if (viewChangeDatas && viewChangeDatas.length > 0) {
            if (activeType) {
                let item = viewChangeDatas.find((bar) => {
                    return bar['type'] === activeType;
                })
                activeTypeItem = item;
            }
            else {
                activeTypeItem = viewChangeDatas[0];
            }
            return activeTypeItem;
        }
        return null;
    }

}
